﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;

namespace TestByWire.AttributeHandlers
{
    internal class AttributeBuildPlan : IAttributeBuildPlan
    {
        private readonly IScopeInformation _scopeInformation;

        public void Execute(object targetInstance, IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            IBuildContext context = new BuildContext(targetInstance, container);
            IEnumerable<IContainerInteraction> netList = GetCrossScopeList();
            foreach (var interaction in netList)
            {
                interaction.Execute(context);
            }

        }

        private IEnumerable<IContainerInteraction> GetCrossScopeList()
        {
            var crossScopeList = new List<IContainerInteraction>(_scopeInformation.GetInteractions(Scope.Dynamic));

            var comparer = new InteractionEqualityComparer();

            foreach (var interaction in _scopeInformation.GetInteractions(Scope.Local))
            {
                if (!crossScopeList.Contains(interaction, comparer))
                    crossScopeList.Add(interaction);
            }

            foreach (var interaction in _scopeInformation.GetInteractions(Scope.Global))
            {
                if (!crossScopeList.Contains(interaction, comparer))
                    crossScopeList.Add(interaction);
            }

            return crossScopeList;
        }

        public AttributeBuildPlan(IScopeInformation scopeInfo)
        {
            if (scopeInfo == null)
            {
                throw new ArgumentNullException("scopeInfo");
            }

            _scopeInformation = scopeInfo;
        }
    }


}
